package com.ruoyi.voucher.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.voucher.dao.PageDao;
import com.ruoyi.voucher.domain.FxyFinancialVoucher;
import com.ruoyi.voucher.domain.FxyFinancialVoucherDetails;
import com.ruoyi.voucher.domain.TbDetail;
import com.ruoyi.voucher.mapper.VoucherMapper;
import com.ruoyi.voucher.service.VoucherService;
import com.ruoyi.voucher.vo.FxyFinancialVoucherDetailsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Author
 * @Date 2025/2/25 9:43
 * @Description:
 */
@Slf4j
@Service
public class VoucherServiceImpl extends ServiceImpl<VoucherMapper, FxyFinancialVoucher> implements VoucherService {
    @Autowired
    VoucherMapper voucherMapper;


    @Override
    @Transactional
    public R insertVoucher(List<FxyFinancialVoucher> fxyFinancialVoucher) {
        // 1. 参数校验
//        if (fxyFinancialVoucher == null) {
//            log.error("传入的凭证对象为空");
//            return R.fail("凭证信息不能为空");
//        }
        // 2. 使用数据流进行校验
        // 2. 使用数据流进行校验

        R validationResult = fxyFinancialVoucher.stream()
                .peek(financialVoucher -> financialVoucher.setCreateDate(new Date()))
                .map(financialVoucher -> {
                    Double debitAmount = financialVoucher.getDebitAmount();
                    Double creditAmount = financialVoucher.getCreditAmount();

                    if (Objects.isNull(debitAmount) || Objects.isNull(creditAmount)) {
                        log.error("借方金额和贷方金额不能为空，借方金额：{}，贷方金额：{}", debitAmount, creditAmount);
                        return R.fail("借方金额和贷方金额不能为空");
                    }

                    if (!Objects.equals(debitAmount, creditAmount)) {
                        log.error("借方金额和贷方金额不一致，借方金额：{}，贷方金额：{}", debitAmount, creditAmount);
                        return R.fail("借方金额和贷方金额需要一致");
                    }
                    int tbDetail = createTbDetail(financialVoucher);
                    System.out.printf("tbDetail {} = " + tbDetail);

                    return null; // 校验通过时不返回任何结果
                })
                .filter(Objects::nonNull) // 过滤出非空的结果（即校验失败的结果）
                .findFirst()
                .orElse(null);

        // 4. 插入凭证
        try {
            int result = voucherMapper.insertVoucher(fxyFinancialVoucher);
            /*进行判断*/
            if (result > 0) {
                log.info("凭证插入成功，凭证信息：{}", fxyFinancialVoucher);
                return R.ok("凭证插入成功");
            } else {
                log.error("凭证插入失败，凭证信息：{}", fxyFinancialVoucher);
                return R.fail("凭证插入失败");
            }
        } catch (Exception e) {
            log.error("凭证插入时发生异常，凭证信息：{}，异常信息：{}", fxyFinancialVoucher, e.getMessage(), e);
            return R.fail("凭证插入时发生异常");
        }

    }

    private int createTbDetail(FxyFinancialVoucher financialVoucher) {
        TbDetail tbDetail = new TbDetail();
        tbDetail.setCreditAmount(financialVoucher.getCreditAmount());
        tbDetail.setWord(financialVoucher.getWord());
        tbDetail.setSubjectId(financialVoucher.getAccountSetsId());
        tbDetail.setDebitAmount(financialVoucher.getDebitAmount());
        tbDetail.setCumulativeCredit(financialVoucher.getCreditAmount() + financialVoucher.getDebitAmount());
        tbDetail.setCumulativeDebit(financialVoucher.getCreditAmount() + financialVoucher.getDebitAmount());
        calculate(tbDetail);
        System.out.printf("tbDetail{} = " + tbDetail);
        return voucherMapper.insertTbDetail(tbDetail);
    }
    private  void calculate (TbDetail gl){
        if (gl.getCreditAmount() > 0) {
            gl.setDirection("借");
            log.info("借");
        } else if (gl.getDebitAmount() < 0) {
            log.info("贷");
            gl.setDirection("贷");
        }
        gl.setDirection("平");
        log.info("平");
        log.info("平");
    }

    public  void  task (TbDetail gl){
        int compareResult = gl.getCreditAmount().compareTo(BigDecimal.ZERO.doubleValue());
        gl.setDirection(compareResult > 0 ? "借" : (compareResult < 0 ? "贷" : "平"));
    }

    @Override
    public List<FxyFinancialVoucherDetailsVo> voucherList(PageDao pageDao) {

        return voucherMapper.voucherList(pageDao);
    }

    @Override
    public List<FxyFinancialVoucherDetails>  detailsList() {
        return voucherMapper.selectDetailsList();
    }

}
                                                                                                                                                                                                                                                                                                                                                                